package api

import (
	"FeedXmh/app/dao"
	jwt "github.com/gogf/gf-jwt"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/gfile"
	"github.com/gogf/gf/text/gstr"
	"github.com/gogf/gf/util/gconv"
	"io"
	"os"
	"path/filepath"
)

var Firmware = firmware{}

type firmware struct{}

func (a *firmware) Get(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}

	params := r.GetQueryMap()
	id := gconv.String(params["id"])
	name := gconv.String(params["name"])
	_type := gconv.String(params["type"])

	where := " 1=1 "
	if id != "" {
		where += " and id=" + id
	}
	if _type != "" {
		where += " and type='" + _type + "'"
	}
	if name != "" {
		where += " and name like '%" + name + "%' "
	}

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path

	if dao.CheckApiPermission(url, r.Method, userid) {
		list, err := dao.T_firmware.GetList(where)

		if err != nil {
			res["code"] = -1
			res["msg"] = err.Error()
		} else {
			res["code"] = 0
			res["data"] = list
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *firmware) Upload(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": "",
	}
	f, h, e := r.FormFile("upload-file")
	if e != nil {
		res["msg"] = e.Error()
		res["code"] = -1
		r.Response.WriteJson(res)
		return
	}
	defer f.Close()

	execpath, _ := os.Executable() // 获得程序路径
	savePath := filepath.Join(filepath.Dir(execpath), "public", "firmware")
	saveFilePath := savePath + "/" + gfile.Basename(h.Filename)
	file, err := gfile.Create(saveFilePath)
	if err != nil {
		res["msg"] = err.Error()
		res["code"] = -1
		r.Response.WriteJson(res)
		return
	}
	defer file.Close()
	if _, err := io.Copy(file, f); err != nil {
		res["msg"] = err.Error()
		res["code"] = -1
		r.Response.WriteJson(res)
		return
	}

	//保存文件成功，写入db
	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	file_type := r.GetString("type")

	name := h.Filename
	file_size := gconv.String(h.Size/1024) + " kb"
	upload_by := userid
	file_path := saveFilePath

	db := g.DB(g.Cfg().GetString("custom.db_name"))
	sqlres, err := db.Model("t_firmware").Data(g.Map{"name": name, "type": file_type, "file_size": file_size, "file_path": file_path, "upload_by": upload_by}).Insert()
	if id, err := sqlres.LastInsertId(); err == nil && id >= 0 {
		all, err := db.GetAll("SELECT * FROM t_firmware WHERE type='" + file_type + "';")
		if err != nil || all == nil {
			res["msg"] = err.Error()
			res["code"] = -1
		} else {
			list := all.List()
			for _, item := range list {
				if gconv.Int(item["id"]) == gconv.Int(id) {
					item["default"] = 1
				} else {
					item["default"] = 0
				}
			}
			_, err := db.Model("t_firmware").Data(list).Save()
			if err != nil {
				res["msg"] = err.Error()
				res["code"] = -1
			}
		}

	} else {
		res["msg"] = err.Error()
		res["code"] = -1
		//删除文件
		gfile.Remove(saveFilePath)
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *firmware) Default(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": "",
	}
	params := r.GetFormMap()
	id, exist := params["id"]
	_type := gconv.String(params["type"])
	if exist {
		claims := jwt.ExtractClaims(r)
		current_user := claims["userid"].(string)
		url := r.URL.Path
		db := g.DB(g.Cfg().GetString("custom.db_name"))
		if dao.CheckApiPermission(url, r.Method, current_user) {
			//设置该类型下所有default=0，然后设置当前为default=1
			all, err := db.GetAll("SELECT * FROM t_firmware WHERE type='" + _type + "';")
			if err != nil || all == nil {
				res["msg"] = err.Error()
				res["code"] = -1
			} else {
				list := all.List()
				for _, item := range list {
					if gconv.Int(item["id"]) == gconv.Int(id) {
						item["default"] = 1
					} else {
						item["default"] = 0
					}
				}
				_, err := db.Model("t_firmware").Data(list).Save()
				if err != nil {
					res["msg"] = err.Error()
					res["code"] = -1
				}
			}
		} else {
			res["code"] = -1
			res["msg"] = "您没有该操作权限"
		}
	} else {
		res["code"] = -1
		res["msg"] = "错误的参数"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *firmware) Delete(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetFormMap()

	id, exist := params["id"]
	file_path := r.GetString("file_path")

	if exist {
		claims := jwt.ExtractClaims(r)
		current_user := claims["userid"].(string)
		url := r.URL.Path
		if dao.CheckApiPermission(url, r.Method, current_user) {
			isok, err := dao.T_firmware.Delete(gconv.String(id))
			if err != nil {
				g.Log().Line().Error(err)
				res["code"] = -1
				res["msg"] = err.Error()
			} else {
				if isok {
					//删除文件
					err := gfile.Remove(file_path)
					if err == nil {
						res["code"] = 1
						res["msg"] = "成功"
					} else {
						res["code"] = -1
						res["msg"] = "失败"
					}
				}
			}
		} else {
			res["code"] = -1
			res["msg"] = "您没有该操作权限"
		}
	} else {
		res["code"] = -1
		res["msg"] = "错误的参数"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *firmware) PUT(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetFormMap()

	claims := jwt.ExtractClaims(r)
	current_user := claims["userid"].(string)
	url := r.URL.Path
	id := gconv.String(params["id"])
	remark := gconv.String(params["remark"])
	//替换\n为<br>
	remark = gstr.Replace(remark, "\n", "<br>")
	//remark = gstr.Replace(remark, `\n`, `<br>`)
	params["remark"] = remark

	if dao.CheckApiPermission(url, r.Method, current_user) {
		//情况对应t_user_group后，重新添加
		db := g.DB(g.Cfg().GetString("custom.db_name"))
		_, err := db.Model("t_firmware").Data(params).Save()
		if err != nil {
			res["code"] = -1
			res["msg"] = err.Error()
		} else {
			res["code"] = 0
			res["msg"] = "保存成功"
			res["data"] = id
		}

	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}
